package com.bonc.common.utils;


import com.jcraft.jsch.SftpProgressMonitor;

import java.text.NumberFormat;
import java.util.concurrent.*;

/**
 * @author kevin.chen
 */
public class UploadMonitorCallable implements SftpProgressMonitor, Callable<Integer> {

    /**
     * 文件的总大小
     */
    private long maxCount = 0;
    private long uploaded = 0;
    long startTime = 0L;

    private boolean isScheduled = false;
    private boolean isEnd=false;



    public UploadMonitorCallable(long maxCount) {
        this.maxCount = maxCount;
    }

    /**
     * 当文件开始传输时，调用init方法
     *
     * @param op
     * @param src
     * @param dest
     * @param max
     */
    @Override
    public void init(int op, String src, String dest, long max) {
        System.out.println("开始上传文件：" + src + "至远程：" + dest + "文件总大小:" + maxCount / 1024 + "KB");
        startTime = System.currentTimeMillis();
    }

    /**
     * 当每次传输了一个数据块后，调用count方法，count方法的参数为这一次传输的数据块大小
     *
     * @param count
     * @return
     */
    @Override
    public boolean count(long count) {
        if (!isScheduled) {
            createTread();
        }
        uploaded += count;
//        System.out.println("本次上传大小：" + count / 1024 + "KB,");
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 当传输结束时，调用end方法
     */
    @Override
    public void end() {
        isEnd=true;
    }

    /**
     * 创建一个线程每隔一定时间，输出一下上传进度
     */
    public void createTread() {

        isScheduled = true;
    }


    @Override
    public Integer call() throws Exception {
        NumberFormat format = NumberFormat.getPercentInstance();
        format.setMaximumFractionDigits(2);
        format.setMinimumFractionDigits(2);
        if(isEnd){
            return 1;
        }
        return 0;
    }
}
